import { isBlank } from '@/utils'

export function ruleRequired (message: string, trigger = '') {
  return {
    required: true,
    message: message,
    trigger,
    validator: (_rule: any, value: any, callback: any) => {
      if (isBlank(value)) {
        return callback(new Error(message))
      }
      callback()
    }
  }
}

export function ruleRequiredInt (message: string) {
  return {
    type: 'number',
    required: true,
    message: message,
    trigger: ['blur', 'change']
  }
}

export function ruleMaxLength (max: number, label = '输入字符') {
  return {
    max,
    message: `${label}不能超过${max}位`,
    trigger: ['blur', 'change']
  }
}

export function ruleMinLength (min: number, label = '请输入') {
  return {
    min,
    message: `${label}至少${min}位字符`,
    trigger: ['blur', 'change']
  }
}

export const IS_NUMBER_DECIMAL_2 = {
  pattern: /^\d+(?:\.\d{0,2})?$/,
  message: '最多两位小数',
  trigger: ['blur', 'change']
}

export const IS_NUMBER = {
  pattern: /^[0-9]+\.?[0-9]*$/,
  message: '请输入数字',
  trigger: ['blur', 'change']
}

export const IS_NUMBER_INTEGER = {
  pattern: /^[0-9]+$/,
  message: '请输入整数数字',
  trigger: ['blur', 'change']
}

export const IS_BIGGERTHAN_ONE = {
  pattern: /^([1-9]\d+|[2-9])$/,
  message: '请输入大于1的正整数',
  trigger: ['blur', 'change']
}

export const IS_CODE = {
  pattern: /^[A-Za-z0-9_]*$/g,
  message: '只能输入英文字母、下划线、数字',
  trigger: ['blur', 'change']
}

export const IS_FILED_CODE = {
  pattern: /^[A-Za-z0-9-_:]*$/g,
  message: '只能输入英文字母、下划线、短横线、数字以及冒号（：）',
  trigger: ['blur', 'change']
}

export const NAME_CN = {
  pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/,
  message: '只能输入中文、英文字母、下划线、数字、短横线',
  trigger: ['blur', 'change']
}

export const RULE_PORT = {
  pattern: /^(0|[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,
  message: '请输入正确的端口号',
  trigger: ['blur', 'change']
}

export const RULE_EMAIL = {
  pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
  message: '邮箱格式不正确',
  trigger: ['blur', 'change']
}

export const RULE_VERSION = {
  pattern: /^v\d+\.\d+\.\d+$/,
  message: '版本号格式不正确',
  trigger: ['blur', 'change']
}
